package com.drodds.game;

import java.util.Random;
import java.util.TreeMap;
import java.util.List;

public class WeightedRandomSelector<T> {
	private final Random rnd = new Random();
	private final TreeMap<Object, Range<T>> ranges = new TreeMap<Object, Range<T>>();
	private int rangeSize;
	
	public WeightedRandomSelector(List<WeightedItem<T>> weightedItems) {
		int bottom = 0;
		
		for(WeightedItem<T> wi : weightedItems) {
			int weight = wi.getWeight();
			if (weight > 0) {
				int top = bottom + weight - 1;
				Range<T> r = new Range<T>(bottom, top, wi);
				if (ranges.containsKey(r)) {
					Range<T> other = ranges.get(r);
					throw new IllegalArgumentException(String.format("Range %s conflicts with range %s", r, other));
				}
				ranges.put(r,r);
				bottom = top+1;
			}
		}
		rangeSize = bottom;
	}
	
	public WeightedItem<T> select() {
		Integer key = rnd.nextInt(rangeSize);
		Range<T> rKey = new Range<T>(key.intValue(), key.intValue(), new WeightedItem<T>(0,null));
		Range<T> r = ranges.get(rKey);
		if (r == null)
			return null;
		return r.weightedItem;
	}
}
